package com.soulgame.notification;

import java.util.Calendar;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;

/**
 * 发送通知类
 * */
public class NotifyUtil implements INotifiContants {
	private static NotificationManager mNotificationManager = null;

	/**
	 * 延迟发送通知
	 * 
	 * @param context
	 * @param pIndexCode
	 *            标记是哪一个通知，在取消通知 cancelDelayNotify 中要使用对应的才可以取消。
	 * @param pTitel
	 *            通知标题
	 * @param pText
	 *            通知内容
	 * @param pIconName
	 *            放在 drawable 下的 图标名称
	 * @param pSoundName
	 *            放在 res/raw 下的 音效名称
	 * 
	 * @param strClassName
	 *            点击通知打开的类名
	 * @param pDelaySeconds
	 *            延迟多少秒执行
	 */
	public static void sendDelayNotify(Context context, int pIndexCode, String pTitel, String pText, String pIconName,
			String pSoundName, String strClassName, int pDelaySeconds) {
		System.out.println("sendDelayNotify pIndexCode=" + pIndexCode);
		//
		AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
		//
		Intent intent = new Intent(context, NotifyReceiver.class);
		intent.setAction(ACTION_NOTIFY);
		intent.putExtra(TITLE, pTitel);
		intent.putExtra(TEXT, pText);
		intent.putExtra(INDEX, pIndexCode);
		intent.putExtra(ICON_NAME, pIconName);
		intent.putExtra(SOUDN_NAME, pSoundName);
		//
		/*Android 3.1开始系统在Intent与广播相关的flag增加了参数，分别是
		FLAG_INCLUDE_STOPPED_PACKAGES和FLAG_EXCLUDE_STOPPED_PACKAGES。
		FLAG_INCLUDE_STOPPED_PACKAGES：包含已经停止的包（停止：即包所在的进程已经退出）
		FLAG_EXCLUDE_STOPPED_PACKAGES：不包含已经停止的包*/
		intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);// 在此设置经过测试貌似没有用，锤子手机退出了收不到，其他手机可以收到

		System.out.println("启动类：" + strClassName);

		if (strClassName != null) {
			intent.putExtra(OPEN_ACTIVITY_NAME, strClassName);
		} else {
			intent.putExtra(OPEN_ACTIVITY_NAME, "");
		}
		//
		long currentTimeMillis = System.currentTimeMillis();
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(currentTimeMillis);
		calendar.add(Calendar.SECOND, pDelaySeconds);
		//
		long timeInMillis = calendar.getTimeInMillis();
		long delayTimes = timeInMillis - currentTimeMillis;
		//
		System.out.println("延迟 " + delayTimes + " 毫秒 Notify");
		//
		PendingIntent pendingIntent = PendingIntent
				.getBroadcast(context, pIndexCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
		// AlarmManager.RTC_WAKEUP表示闹钟在睡眠状态下会唤醒系统并执行提示功能，该状态下闹钟使用绝对时间，状态值为0；
		manager.set(AlarmManager.RTC_WAKEUP, timeInMillis, pendingIntent);

	}

	/**
	 * 取消延迟的通知
	 * 
	 * @param context
	 * @param pIndexCode
	 *            指定需要取消哪一个通知，同sendDelayNotify 中的 pIndexCode 一致
	 */
	public static void cancelDelayNotify(Context context, int pIndexCode) {
		System.out.println("cancelDelayNotify pIndexCode=" + pIndexCode);

		AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
		//
		Intent intent = new Intent(context, NotifyReceiver.class);
		intent.setAction(ACTION_NOTIFY);

		PendingIntent sender = PendingIntent.getBroadcast(context, pIndexCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
		if (sender != null) {
			System.out.println("cancel alarm");
			manager.cancel(sender);
		} else {
			System.out.println("sender == null");
		}
	}

	/**
	 * 发送通知
	 * 
	 * @param context
	 * @param index
	 * @param title
	 * @param text
	 * @param icon
	 * @param strClassName
	 */
	public static void sendNotify(Context context, int index, String title, String text, String iconName, String soundName,
			String strClassName) {
		if (mNotificationManager == null) {
			mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		}
		//
		NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
		mBuilder.setContentIntent(getDefalutIntent(context, Notification.FLAG_AUTO_CANCEL));
		mBuilder.setWhen(System.currentTimeMillis());
		//
		mBuilder.setPriority(Notification.PRIORITY_DEFAULT);
		// 设置是否不可以侧滑清除 false 可以清除
		mBuilder.setOngoing(false);
		//
		mBuilder.setAutoCancel(true);
		mBuilder.setContentTitle(title);
		mBuilder.setContentText(text);
		// mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
		// mBuilder.setDefaults(Notification.DEFAULT_ALL);
		// mBuilder.setVibrate(new long[]{2000,1000,4000}); //需要真机测试
		// mBuilder.setLights(argb, onMs, offMs);
		int iconResId = 1;
		iconResId = context.getResources().getIdentifier(iconName, "drawable", context.getPackageName());
		if (iconResId == 0) { // iconResId 测试过如果是0时，通知不出来，其他时会使用默认图标
			iconResId = 1;
		}
		System.out.println("iconResId=" + iconResId);
		mBuilder.setSmallIcon(iconResId);
		//
		int soundId = context.getResources().getIdentifier(soundName, "raw", context.getPackageName());
		System.out.println("soundId=" + soundId);
		mBuilder.setSound(Uri.parse("android.resource://" + context.getPackageName() + "/" + soundId));

		Class<?> classInfo = null;
		try {
			classInfo = Class.forName(strClassName);
		} catch (Exception e) {
			e.getCause().printStackTrace();
		}

		if (classInfo != null) {
			System.out.println("classInfo != null");
			Intent resultIntent = new Intent(context, classInfo);
			resultIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
			PendingIntent pendingIntent = PendingIntent.getActivity(context, index, resultIntent,
					PendingIntent.FLAG_UPDATE_CURRENT);
			mBuilder.setContentIntent(pendingIntent);
		}

		Notification mNotification = mBuilder.build();
		mNotification.defaults |= Notification.DEFAULT_VIBRATE;
		mNotification.defaults |= Notification.DEFAULT_LIGHTS;

		mNotificationManager.notify(index, mNotification);
	}

	private static PendingIntent getDefalutIntent(Context context, int flags) {
		PendingIntent pendingIntent = PendingIntent.getActivity(context, 1, new Intent(), flags);
		return pendingIntent;
	}
}
